﻿using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using static IdentityModel.OidcConstants;

namespace Batman.Web.Api.Client.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class TokenController : ControllerBase
    {
        IConfiguration Configuration;

        public TokenController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public async Task<IActionResult> Get()
        {

            var cache = new DiscoveryCache("https://localhost:44338");
            var disco = await cache.GetAsync();
            var client = new HttpClient();

            //var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            //{
            //    Address = disco.TokenEndpoint,

            //    ClientId = Configuration["ID4Server:ClientId"],
            //    ClientSecret = Configuration["ID4Server:ClientSecret"],
            //    //Scope = "scope1",
            //    UserName = "admin",
            //    Password = "admin@123",
            //    GrantType = GrantTypes.ClientCredentials
            //});

            var response = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId = Configuration["ID4Server:ClientId"],
                ClientSecret = Configuration["ID4Server:ClientSecret"],
                //Scope = "api1.weather.scope",
                GrantType = GrantTypes.ClientCredentials
            });

            //var response = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            //{
            //    Address = disco.TokenEndpoint,

            //    ClientId = Configuration["ID4Server:ClientId"],
            //    ClientSecret = Configuration["ID4Server:ClientSecret"],
            //    //Scope = IdentityServerConstants.StandardScopes.OpenId + " scope1 api1",
            //    //UserName = "admin",
            //    //Password = "admin@123",
            //    //GrantType = GrantTypes.ClientCredentials
            //});

            var client2 = new HttpClient();
            client2.SetBearerToken(response.AccessToken);
            client2.DefaultRequestHeaders.Add("Bearer", response.AccessToken);
            var response2 = await client2.GetAsync("http://localhost:6298/WeatherForecast");
            //var response2 = await client2.GetAsync(disco.UserInfoEndpoint);
            var content = await response2.Content.ReadAsStringAsync();
            //return Content(response.Raw);
            var res = $"${response.HttpStatusCode}===={ response.Raw}";
            return Content(res + "\n" + content + " " + response2.StatusCode);
        }
    }
}
